import Layout from '@/layout/index.vue';
import type { RouteRecordRaw } from 'vue-router'

/* 获取所有子路由 */
const getChildrenRoutes = (routes: RouteRecordRaw[]) => {
  const childrenRoutes: RouteRecordRaw[] = []
  routes.forEach(route => {
    if (route.children && route.children.length > 0) {
      childrenRoutes.push(...route.children)
    }
  })
  return childrenRoutes
}


/* 处理重复路由 */
export const filterRoutes = (routes: RouteRecordRaw[])  => {
  // 所有的子集路由
  const childrenRoutes = getChildrenRoutes(routes)
  // 根据子集路由进行查重操作
  return routes.filter(route => {
    return !childrenRoutes.find(childrenRoute => {
      return childrenRoute.path === route.path
    })
  })
}

/* 处理从后端传过来的路由数据 */
export const formatRoutes = (routes: any[]) => {
  const formatedRoutes: RouteRecordRaw[] = []
  routes.forEach(route => {
      formatedRoutes.push(
        {
          ...route,
          component: Layout,
          children: route.children.map((child: any) => {
            return {
              ...child,
              component: () => import(`@/views${child.component}`),
            }
          }),
        }
      )
  })
  return formatedRoutes;
}